<?php
/**
 * 任务过程办理  所有工作操作类
 * 
 */
namespace Admin\Controller;

class TaskProcessController extends AbstractController  {
	
	public $isNoBJ = true;  //任务是否需要办结
	public $FrontProcess = array();
	
	//表单名 对应 控制器
	public $ControArr = array(
		//"Project" => "ProjectGL&a=save&type=edit&id=",
		//"ProjectSummary" => "ProjectSummary&a=save&type=table&id="
	);

	public function _initialize(){
		
    }
    
    /**
     * 
     * 根据任务ID查询最终的表彰列表
     */
	public function getFormListByTid(){
		$idStr = "";
		$TID = I('TID') ? (int)I('TID') : 0;
		$sql = " SELECT distinct(FormID) FROM formcontrol WHERE ID IN (SELECT ControlID FROM bp_form_right WHERE BPID = (SELECT b.ID FROM process AS a LEFT JOIN businessprocess AS b ON a.BPID = b.ID WHERE a.TID = {$TID} AND a.Status = 1 AND a.UserID = ".session('USER_ID')." ORDER BY ID DESC LIMIT 1))";
		$res = M()->query($sql);
		foreach($res AS $k => $v){
			$idStr .= $v['FormID'].',';
		}
		if($idStr != "") $idStr = substr($idStr,0,-1);
		$Form = M("form");
		$res1 = $Form->field('*')->where(array("ID"=>array("IN",$idStr),"IsDel"=>0))->select();
		$sql3 = "SELECT b.Name AS BPName,a.ID AS PRID,b.ID AS BPID FROM process AS a LEFT JOIN businessprocess AS b ON a.BPID = b.ID WHERE a.TID = {$TID} AND a.Status = 1  AND a.UserID = ".session('USER_ID')." ORDER BY a.ID ASC LIMIT 1";
		$res3 = M()->query($sql3); //当前人员 正在办理的过程对应的流程ID,流程名称、 和正在办理的过程ID。
		foreach($res1 AS $k => $v){
			$Name = substr($v['Name'],-3,3);
			if($Name == "add" || $Name == "ave"){
				$res1[$k]['url'] = "/index.php?m=Admin&".$v['Name']."&busid=".$res3[0]['BPID']."&formid=".$v['ID'];
			}else{
				$res2 = M("project")->field("ID")->where(array("TID"=>$TID))->order('ID DESC')->limit("1")->find();  //获取当前任务的项目ID
				$res1[$k]['url'] = "/index.php?m=Admin&".$v['Name']."&id=".$res2['ID']."&busid=".$res3[0]['BPID']."&formid=".$v['ID'];
			}
		}
		$return['list'] = $res1;
		$return['PRID'] = $res3[0]['PRID'];
		$return['BPName'] = $res3[0]['BPName'];
		return $this->ajaxReturn($return);
	}
	
	
	/**
	 * 
 	 * 根据流程ID和表单ID查询 控件权限
 	 */
 	public function getRihtByXid(){
 		$BUSID = I('busid') ? (int)I('busid') : 0;
 		$FORMID = I('formid') ? (int)I('formid') : 0;
 		$sql = "SELECT a.RightType,b.CName,b.IDName FROM bp_form_right AS a LEFT JOIN formcontrol AS b ON a.ControlID = b.ID WHERE a.BPID = ".$BUSID." AND b.FormID = ".$FORMID;
 		$res = M()->query($sql);
 		return $this->ajaxReturn($res);
 	}
 	
 	/**
 	 * 
 	 * 保存过程意见信息
 	 */
 	public function addProcessContent(){
 		$data['Content'] = I("Content");
		$PRID = (int)I("PRID");
 		$res = M('process')->where(array("ID"=>$PRID))->save($data); 
 	}
 	
 	
 	/**
 	 * 
 	 *  查询 全部过程意见
 	 */
 	public function getProcessContent(){
 		$TID = (int)I("TID");
 		$PResultArr = array("不同意","同意","其他意见");
 		$res = M('process as a')->field("b.Name,a.Content,a.PResult,c.UserName")->join(" LEFT JOIN businessprocess AS b ON a.BPID = b.ID LEFT JOIN user AS c ON a.UserID = c.ID")->where(array("a.TID"=>$TID))->select();
 		foreach($res AS $k => $v){
 			$res[$k]['PResult'] = $PResultArr[$v['PResult']];
 		}
 		return $this->ajaxReturn($res);
 	}
 	
 	
 	/**
 	 * 
 	 * 办结 流程
 	 */
 	public function BanjieProcess($PRID = false, $TID = false, $type = false){ 		
 		//修改流程状态	
 		if($type == false){
 			
 			//办结前先查询当前流程的目录是否是必传附件，如果是就查询该目录是否已经上传了附件，（或者其它流程是否帮当前流程的目录上传了附件）。
 			$RES1 = M("process")->field("BPID")->where(array("ID"=>$PRID))->find();
 			$RES2 = M("bp_attachment_list")->field("distinct(BALID)")->where(array("BPID"=>$RES1['BPID'],"IsInput"=>2))->select();
 			foreach($RES2 AS $K => $V){
 				$sql = "SELECT * FROM task_attachment_list WHERE BALID = {$V['BALID']} AND TID = {$TID} AND IsDel = 0";
 				$RES3 = M()->query($sql);
 				if(empty($RES3)){
 					$this->error('请先上传附件之后再办结');
 					exit();
 				}
 			}
 			$data['Status'] = 2;
 			$data['PResult'] = 1;
 			$data['EndTime'] = date("Y-m-d H:i:s");
 			M("process")->where(array("ID"=>(int)$PRID))->save($data);
 		}
 		$Pres = M("process")->field("ID,PPID,Status")->where(array("PPID"=>$PRID,"TID"=>$TID,"IsDel"=>0))->select();
 		foreach($Pres AS $k => $v){ //循环同级流程
 			if($v['Status'] == 2){ //已经办结的流程
 				$this->BanjieProcess($v['ID'],$v['PPID'],true); //断续住下查询 需要开启的流程
 			}else{ //需要开启 或 进行中的流程
 				$data = array();
 				$data['Status'] = 1;
 				M("process")->where(array("ID"=>$v['ID']))->save($data);
 			}
 		}
 		//查询该任务 是否已经办结所有流程
 		if($type == false){
 			$res = $this->setAllIsBanjie($TID,0);
 			if($this->isNoBJ){// 办结任务
 				$data = array();
 				$data['EndTime'] = date("Y-m-d H:i:s");
 				$data['Status'] = 1;
 				M("task")->where(array("ID"=>$TID))->save($data);
 			}
 		}
		$this->success('操作成功');
 	}
 	
 	
 	/**
 	 * 
 	 * 查询该任务 是否已经办结所有流程
 	 */
 	public function setAllIsBanjie($TID,$ID){
 		$Pres = M("process")->field("ID,PPID,TID,Status")->where(array("PPID"=>$ID,"TID"=>$TID,"IsDel"=>0))->select();
 		foreach($Pres AS $k => $v){
 			if($v['Status'] != 2){
 				$this->isNoBJ = false;
 			}else{
 				$this->setAllIsBanjie($v["TID"],$v["ID"]);
 			}
 		}
 	}
 	
 	
 	/**
 	 * 
 	 * 查询前面的流程
 	 */
 	public function getFrontProcess($PRID,$TID){
 		$idStr = "";
 		$retuArr = array();
 		$this->getFrontProcessA($PRID,$TID);
 		foreach($this->FrontProcess AS $k => $v){
 			if($v != NULL && $v['ID'] != $PRID){
 				//$retuArr
 				$idStr .= $v['ID'].",";
 			}
 		}
 		if($idStr){
 			$res = M("process as a")->field("a.ID,b.Name")->join("LEFT JOIN businessprocess AS b ON a.BPID = b.ID")->where(array("a.ID"=>array("IN",substr($idStr,0,-1)),"a.IsDel"=>0))->select();
 		}else{
 			$res['status'] = 0;
 			$res['info'] = "没有前面流程";
 		}
 		return $this->ajaxReturn($res);
 	}
 	
 	public function getFrontProcessA($PRID,$TID){
 		$Pres = M("process")->field("ID,PPID,TID,Status")->where(array("ID"=>$PRID,"TID"=>$TID,"IsDel"=>0))->find();
 		$this->FrontProcess[] = $Pres;
 		if(!empty($Pres)){
 			$this->getFrontProcessA($Pres["PPID"],$Pres["TID"]);
 		}
 	}
 	
 	
 	/**
 	 * 
 	 * 流程返回
 	 */
 	public function ReturnPprocess(){
 		$PResult = I('PResult') ? (int)I('PResult') : 1;
 		$data['LBPID'] = I('LBPID') ? (int)I('LBPID') : 0;
 		$data['RBPID'] = I('RBPID') ? (int)I('RBPID') : 0;
 		$data['ReturnReaso'] = I('ReturnReaso') ? I('ReturnReaso') : "";
 		$data['ReturnTime'] = date("Y-m-d H:i:s");
		M("processreturn")->data($data)->add();
		$updata['Status'] = 1;
		M("process")->where(array("ID"=>$data['RBPID']))->save($updata);
		$update['Status'] = 0;
		$update['PResult'] = $PResult;
		M("process")->where(array("ID"=>$data['LBPID']))->save($update);
		$this->success('操作成功');
 	}
 	
 	
 	/**
 	 * 任务提前办结申请
 	 * 
 	 */
 	public function TaskApplyEnd(){
 		$data = array();
 		$PRID = I('PRID') ? (int)I('PRID') : 0;
 		$PResult = I('PResult') ? (int)I('PResult') : 1;
 		$res = M("process as a")->field("b.ID")->join("LEFT JOIN businessprocess AS b ON a.BPID = B.ID")->where(array("a.ID"=>$PRID))->find();
		$data['BPID'] = $res['ID'];
		$data['Reason'] = I('Reason') ? I('Reason') : "";
		$data['ApplyTime'] = date("Y-m-d H:i:s");
 		M("taskapplyend")->data($data)->add();
 		$update['Status'] = 0;
 		$update['PResult'] = $PResult;
 		M("process")->where(array("ID"=>$PRID))->save($update);
 		$this->success('操作成功');
 	}
 	
 	/**
 	 *  文件上传
 	 * 
 	 */
 	public function EnclosureUpFile(){
 		if($_FILES){
 			$return = array();
    		$rtn = "";
    		$config = array(
    			'maxSize' => 5*1024*1024,
    			'rootPath' => './data/upload/Task/Enclosure/',
    			'savePath' => '',
    			'saveName' => array('uniqid',''),
    			'exts' => array('rar','zip','doc','xls','docx','xlsx','pdf','txt','png','jpg'),
    			'autoSub' => true,
    			'subName' => array('date','Ymd')
    		);
    		$this->mkdirs($config['rootPath']);
	    	$upload = new \Think\Upload($config);// 实例化上传类
	    	// 上传文件
	    	$info = $upload->upload($_FILES);
	    	if(!$info) {// 上传错误提示错误信息
	    		$rtn = $this->error($upload->getError());
	    	}else{// 上传成功
	    		foreach ($info as $key=>$img){
	    			if($key==0){
	    				$rtn .= $config['rootPath'].$img['savepath'].$img['savename'];
	    			}else{
	    				$rtn .= "|".$config['rootPath'].$img['savepath'].$img['savename'];
	    			}
	    		}
	    	}
	    	

	    	//先增加任务附件目录表
	    	$datas['TID'] = (int)$_GET["TID"];
	    	$datas['BALID'] = (int)$_GET["BALID"];
	    	$TALID = M("task_attachment_list")->data($datas)->add();
	    	//再增加任务附件表
	    	$data['TALID'] = $TALID;
	    	$data['Name'] = $img['name'];
	    	$data['SavePath'] = $rtn;
	    	$data['UserID'] = session('USER_ID');
	    	$data['AddTime'] = date("Y-m-d H:i:s");
	    	$res = M("taskattachment")->data($data)->add();
			if($res){
				$return['code'] = 1;
				$return['msg'] = "上传成功";
				$return['data']['src'] = $rtn;
				$return['data']['BALID'] = $datas['BALID'];
			}else{
				$return['code'] = 0;
				$return['msg'] = "上传失败";
			}
			return $this->ajaxReturn($return);
    	}
    }
    
    
    /**
     * 查询当前流程的附件目录列表
     * 
     */
	public function getCatalogListByPRID(){
		$TID = I('TID') ? (int)I('TID') : 0;
		$PRID = I('PRID') ? (int)I('PRID') : 0;
		//这是该流程 属于自己禁止显示的目录
		$res = M()->query("SELECT * FROM business_attachment_list WHERE ID IN(SELECT c.BALID FROM process AS a LEFT JOIN businessprocess AS b ON a.BPID = b.ID LEFT JOIN bp_attachment_list AS c ON b.ID = c.BPID WHERE a.ID = {$PRID} AND c.IsShow = 0 AND a.IsDel = 0) AND IsDel = 0");
		//这是该任务 所有流程 绑定的所有目录
		$res1 = M()->query("SELECT * FROM business_attachment_list WHERE ID IN(SELECT c.BALID FROM process AS a LEFT JOIN businessprocess AS b ON a.BPID = b.ID LEFT JOIN bp_attachment_list AS c ON b.ID = c.BPID WHERE a.TID = {$TID}) AND IsDel = 0 ORDER BY ID DESC");
		 //从任务目录  移除流程自己禁止显示的目录
		foreach($res1 AS $k => $v){
			foreach($res AS $K => $V){
				if($v['ID'] == $V['ID']){
					unset($res1[$k]);
				}
			}
		}
		return $this->ajaxReturn($res1);
	}
	
	/**
	 * 查询当前流程的附件目录 的附件列表
	 * 
	 */
	public function getFJListByPRID(){
		$return = array();
		$TID = I('TID') ? (int)I('TID') : 0;
		$BALID = I('BALID') ? (int)I('BALID') : 0;
		$PRID = I('PRID') ? (int)I('PRID') : 0;
		//"task_attachment_listg表少个(流程ID)BPID字段   ，因为 无法知道 该目录的附件属于哪 流程  ，  这样会出现不同流程操作 相同目录的附件"   
		$res1 = M("task_attachment_list as a")->field("b.*,(SELECT UserName FROM user WHERE ID = b.UserID) AS UserName")->join("LEFT JOIN TaskAttachment AS b ON a.ID = b.TALID")->where(array("a.TID"=>$TID,"a.BALID"=>$BALID,"a.IsDel"=>0))->select();
		//echo M("task_attachment_list as a")->getLastSql();
		//var_dump($res1);
		foreach($res1 AS $k => $v){ //过滤掉没有数据的部分
			if($v['ID'] == NULL) unset($res1[$k]);
		}
		$res2 = M("process")->field("BPID")->where(array("TID"=>$TID,"ID"=>$PRID))->find();
		$res3 = M("bp_attachment_list")->field("IsInput")->where(array("BPID"=>$res2['BPID'],"BALID"=>$BALID))->find();
		foreach($res1 AS $k => $v){
			$file_path = pathinfo($v['SavePath']);
			if($file_path['extension'] == "jpg" || $file_path['extension'] == "png" || $file_path['extension'] == "gif"){
				$res1[$k]['isPicture'] = 1; 
			}else{
				$res1[$k]['isPicture'] = 0; 
			}
		}
		$return['list'] = $res1;
		$return['IsInput'] = ($res3['IsInput'] != NULL) ? $res3['IsInput'] : -1;
		return $this->ajaxReturn($return);
	}
    
    
    /**
     *  附件下载
     * 
     */
    public function EnclosureDownload(){
    	$ID = I('ID') ? (int)I('ID') : 0;
    	$res = M('taskattachment')->field('SavePath,Name')->where(array("ID"=>$ID))->find();
    	import('Org.Net.Http');
    	$Http = new \Org\Net\Http();
    	$Http::download($res['SavePath'],$res['Name']);
    }
    
    /**
     * 附件删除
     * 
     */
    public function EnclosureDelet(){
    	$ID = I('ID') ? (int)I('ID') : 0;
    	$res = M('taskattachment')->field('TALID')->where(array("ID"=>$ID))->find();
    	$update['IsDel'] = 1;
 		$RES = M("task_attachment_list")->where(array("ID"=>$res['TALID']))->save($update);
 		if($RES){
 			$this->success('操作成功');
 		}else{
 			$this->error('操作失败');
 		}
 		
    }
    
}